import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';

@Injectable()
export class RoleService {

    constructor(
        @InjectRepository(Role)
        private readonly roleRepository: Repository<Role>
    ) { }

    async create(body: any) {
        const { name: role_name, description, routes } = body
        return {
            code: 200,
            data: await this.roleRepository.save({
                role_name,
                description,
                routes: JSON.stringify(routes)
            })
        }
    }

    async remove(id: number) {//如果该角色下有用户，则需要先删除该角色下的用户
        try {
            return {
                code: 200,
                data: await this.roleRepository.delete({ id })
            }
        } catch (error) {
            return {
                code: 200,
                data: {
                    error
                }
            }
        }
    }

    async getRoles(query: any) {
        const { skip, take } = query;
        const [roles, totalCount] = await this.roleRepository.findAndCount({ skip, take });
        let data = [];
        roles.forEach(role => {
            data.push({
                key: role.id,
                name: role.role_name,
                description: role.description,
                routes: JSON.parse(role.routes)
            })
        })
        return {
            code: 200,
            data: [
                data,
                totalCount
            ]
        };
    }

    async update(id: number, body: any) {
        console.log('====================================');
        console.log(body);
        console.log('====================================');
        const { name: role_name, description, routes } = body
        return {
            code: 200,
            data: await this.roleRepository.update(id, { role_name, description, routes: JSON.stringify(routes) })
        }
    }

    async getAllRoutes() {
        const { routes } = await this.roleRepository.findOne({ where: { id: 1 } })
        return {
            code: 200,
            data: JSON.parse(routes)
        }
    }

}
